package staticClass;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.os.Looper;
import android.util.Log;

public class MyRequest {
	public static String responseStr;
	public static void postDataJson(final String serverURL, final JSONObject json) {
		Thread t = new Thread() {
			public void run() {
				Looper.prepare(); // For Preparing Message Pool for the child
									// Thread
				HttpClient client = new DefaultHttpClient();
				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						10000); // Timeout Limit
				HttpResponse response;
//				JSONObject json = new JSONObject();

				try {
					HttpPost post = new HttpPost(serverURL);
					StringEntity se = new StringEntity(json.toString());
					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
							"application/json; charset=utf-8"));
					post.setEntity(se);
					String postStr = convertStreamToString(post.getEntity().getContent()).replace("\n", ""); 
					Log.i("postDataJson", "request: url:"+serverURL + " " + 
							postStr);
					response = client.execute(post);

					/* Checking response */
					if (response != null) {
						InputStream in = response.getEntity().getContent(); // Get
																			// the
																			// data
																			// in
																			// the
																			// entity
						String responseStr = convertStreamToString(in).replace("\n", "");
						Log.i("postDataJson", "response: " + responseStr);
					}

				} catch (Exception e) {
					Log.i("postDataJson",
							"ex: " + e.getMessage() + " "
									+ e.getLocalizedMessage());
				}

				Looper.loop(); // Loop in the message queue
			}
		};
		t.start();
	}
	
	public static String convertStreamToString(InputStream is) throws Exception{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	    StringBuilder sb = new StringBuilder();
	    String line = null;
	    while ((line = reader.readLine()) != null) {
	        sb.append(line + "\n");
	    }
	    is.close();
	    return sb.toString();
	}
	
	
}
